package com.tencent.shadow.sample.host;

import android.app.Activity;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelStore;
import androidx.lifecycle.ViewModelStoreOwner;
import androidx.multidex.MultiDex;

import com.meichis.mcsappframework.BaseApplication;
import com.meichis.mcsappframework.utils.SharePreferenceUtil;
import com.meichis.mcsappframework.utils.Tools;
import com.tencent.shadow.sample.host.model.UserInfo;
import com.tencent.shadow.sample.host.plugin.UserPlugin;
import com.tencent.shadow.sample.introduce_shadow_lib.InitApplication;

import java.util.UUID;

public class MCApplication extends BaseApplication implements ViewModelStoreOwner {

    private ViewModelProvider.Factory mFactory;
    private ViewModelStore viewModelStore;
    public static String DeviceID = "";

    @Override
    public void onCreate() {
        super.onCreate();

        viewModelStore = new ViewModelStore();

        InitApplication.onApplicationCreate(this);

        MultiDex.install(this);

        getDeviceID();

        UserPlugin.Impl.Impl = new UserPlugin() {
            @Override
            public void setUserInfo(UserInfo userInfo) {

            }
        };

    }

    private void getDeviceID() {
        DeviceID = Tools.getDeviceId(this);
        if (TextUtils.isEmpty(DeviceID) || DeviceID.equals("unknown") || DeviceID.equals("ANDROID_ID_IS_NULL")) {
            DeviceID = SharePreferenceUtil.getInstance().getStringValue("DeviceID");
            if (TextUtils.isEmpty(DeviceID)) {
                DeviceID = UUID.randomUUID().toString();
                SharePreferenceUtil.getInstance().setStringValue("DeviceID", DeviceID);
            }
        }
    }

    /**
     * 暴露出去 对外提供唯一一份的ViewModelProvider
     *
     * @param activity
     * @return
     */
    public ViewModelProvider getAppViewModelProvider(Activity activity) {
        return new ViewModelProvider((MCApplication) activity.getApplicationContext(),
                ((MCApplication) activity.getApplicationContext()).getAppFactory(activity));
    }

    private ViewModelProvider.Factory getAppFactory(Activity activity) {
        if (mFactory == null) {
            mFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(activity.getApplication());
        }
        return mFactory;
    }

    @NonNull
    @Override
    public ViewModelStore getViewModelStore() {
        return viewModelStore;
    }
}
